import cv2
import numpy as np

img = cv2.imread('1.jpg', cv2.IMREAD_GRAYSCALE)
ret,thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
kernel = np.ones((3,3), np.uint8)
##礼帽 = 原始图-开运算   相当于保留刺
new_img = cv2.morphologyEx(thresh1, cv2.MORPH_TOPHAT, kernel)
## 黑帽 = 闭运算-原始图  相当于保留边框
new_img1 = cv2.morphologyEx(thresh1, cv2.MORPH_BLACKHAT, kernel)
all_img = np.hstack([thresh1, new_img,new_img1])
cv2.imshow('all_img',all_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
